package cz.muni.fi.pa165.library.client.gui.swing;

import cz.muni.fi.pa165.library.api.Available;
import cz.muni.fi.pa165.library.api.BookService;
import cz.muni.fi.pa165.library.api.BookTO;
import cz.muni.fi.pa165.library.api.Genre;
import cz.muni.fi.pa165.library.api.State;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author xfoltyn
 */
public class BookPanel extends JPanel {

    private BookService bookWebService;
    
    private BookPanel bookPanel;
    
    private JButton addBookButton, createBookButton, removeBookButton, updateBookButton;
    private DefaultTableModel model;
    private JPanel createPanel;
    private JFrame frameCreate;
    private JTable table;
    private BookTO book;
    private JComboBox genreField, statusField;
    private JTextField titleField, authorField, isbnField, publicationYearField, publicationPlaceField, publisherField;
    private JLabel titleLabel, statusLabel, authorLabel, isbnLabel, genreLabel, publicationYearLabel, publicationPlaceLabel, publisherLabel;

    public BookPanel(BookService bookWebService) {
        this.bookWebService = bookWebService;
        bookPanel = this;
        
        initializeComponents();

        setLayout(null);
        addBookButton.setBounds(50, 20, 150, 20);
        add(addBookButton);
        removeBookButton.setBounds(220, 20, 150, 20);
        add(removeBookButton);
        updateBookButton.setBounds(390, 20, 150, 20);
        add(updateBookButton);
        JScrollPane pane = new JScrollPane(table);

        pane.setBounds(50, 50, 670, 300);
        add(pane);
    }

    private void parseBook(List<BookTO> list) {
        Iterator it = list.listIterator();
        while (it.hasNext()) {
            BookTO bookTO = (BookTO) it.next();
            Object[] bookRow = {
                bookTO.getId(), bookTO.getAuthor(), bookTO.getTitle(), bookTO.getISBN(), bookTO.getAvailability(), bookTO.getGenre(),
                bookTO.getPublicationPlace(), bookTO.getPublicationYear(), bookTO.getPublisher(), bookTO.getStatus()
            };
            model.addRow(bookRow);
        }
    }

    private void bookTable() {
        model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        model.addColumn("Id");
        model.addColumn("Author");
        model.addColumn("Title");
        model.addColumn("ISBN");
        model.addColumn("Available");
        model.addColumn("Genre");
        model.addColumn("Publication Place");
        model.addColumn("Publication Year");
        model.addColumn("Publisher");
        model.addColumn("Status");
        try {
            List<BookTO> list = bookWebService.findAllBooks();
            if (list != null) {
                parseBook(bookWebService.findAllBooks());
            }
        } catch (NullPointerException ex) {
            JOptionPane.showMessageDialog(bookPanel, "Cannot read books.\nServer connection problem.",
                    "Oops!", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void initializeComponents() {
        bookTable();
        table = new JTable(model);

        addBookButton = new JButton("Create book");
        addBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frameCreate = new JFrame("Create book");
                frameCreate.add(new JScrollPane(createBook()), BorderLayout.CENTER);
                frameCreate.setVisible(true);
                frameCreate.setSize(new Dimension(400, 450));
                frameCreate.setLocation(Utils.getPointToCenterApplication(400, 450));
            }
        });
        addBookButton.setVisible(true);

        updateBookButton = new JButton("Update book");
        updateBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedRow() != -1) {
                    frameCreate = new JFrame("Update book");
                    frameCreate.add(new JScrollPane(updateBook()), BorderLayout.CENTER);
                    frameCreate.setVisible(true);
                    frameCreate.setSize(new Dimension(400, 500));
                    frameCreate.setLocation(Utils.getPointToCenterApplication(400, 500));
                }
            }
        });
        updateBookButton.setVisible(true);

        removeBookButton = new JButton("Remove book");
        removeBookButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (table.getSelectedRow() != -1) {
                    Long id = (Long) model.getValueAt(table.getSelectedRow(), 0);
                    try {
                        bookWebService.deleteBook(bookWebService.findBookById(id));
                        model.removeRow(table.getSelectedRow());
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(bookPanel, "Cannot remove book.\nServer connection problem.",
                                "Oops!", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        removeBookButton.setVisible(true);
    }

    private JPanel updateBook() {
        Long id = (Long) model.getValueAt(table.getSelectedRow(), 0);
        createPanel = new JPanel();
        book = new BookTO();
        try {
            book = bookWebService.findBookById(id);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(bookPanel, "Cannot update book.\nServer connection problem.",
                    "Oops!", JOptionPane.ERROR_MESSAGE);
        }

        createPanel.setLayout(null);

        titleField = new JTextField(book.getTitle());
        authorField = new JTextField(book.getAuthor());
        isbnField = new JTextField(book.getISBN());
        genreField = new JComboBox(Genre.values());
        genreField.setSelectedItem(book.getGenre());
        statusField = new JComboBox(State.values());
        statusField.setSelectedItem(book.getStatus());
        publicationYearField = new JTextField(book.getPublicationYear());
        publicationPlaceField = new JTextField(book.getPublicationPlace());
        publisherField = new JTextField(book.getPublisher());

        titleLabel = new JLabel("Title");
        authorLabel = new JLabel("Author");
        isbnLabel = new JLabel("ISBN");
        statusLabel = new JLabel("State");
        genreLabel = new JLabel("Genre");
        publicationYearLabel = new JLabel("Publication year");
        publicationPlaceLabel = new JLabel("Publication place");
        publisherLabel = new JLabel("Publisher");

        titleLabel.setBounds(10, 15, 150, 20);
        createPanel.add(titleLabel);
        titleField.setBounds(10, 35, 150, 20);
        createPanel.add(titleField);

        authorLabel.setBounds(10, 60, 150, 20);
        createPanel.add(authorLabel);
        authorField.setBounds(10, 80, 150, 20);
        createPanel.add(authorField);

        isbnLabel.setBounds(10, 105, 150, 20);
        createPanel.add(isbnLabel);
        createPanel.add(isbnField);
        isbnField.setBounds(10, 125, 150, 20);

        genreLabel.setBounds(10, 150, 150, 20);
        createPanel.add(genreLabel);
        createPanel.add(genreField);
        genreField.setBounds(10, 170, 150, 20);

        publicationYearLabel.setBounds(10, 195, 150, 20);
        createPanel.add(publicationYearLabel);
        createPanel.add(publicationYearField);
        publicationYearField.setBounds(10, 215, 150, 20);

        publicationPlaceLabel.setBounds(10, 240, 150, 20);
        createPanel.add(publicationPlaceLabel);
        createPanel.add(publicationPlaceField);
        publicationPlaceField.setBounds(10, 260, 150, 20);

        publisherLabel.setBounds(10, 285, 150, 20);
        createPanel.add(publisherLabel);
        createPanel.add(publisherField);
        publisherField.setBounds(10, 305, 150, 20);

        statusLabel.setBounds(10, 330, 150, 20);
        createPanel.add(statusLabel);
        createPanel.add(statusField);
        statusField.setBounds(10, 350, 150, 20);

        createBookButton = new JButton("Update book");
        createBookButton.setBounds(10, 400, 150, 20);
        createPanel.add(createBookButton);
        createBookButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boolean check = true;
                if (titleField.getText().equals("")) {
                    titleField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (authorField.getText().equals("")) {
                    authorField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (isbnField.getText().equals("")) {
                    isbnField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publicationYearField.getText().equals("")) {
                    publicationYearField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publicationPlaceField.getText().equals("")) {
                    publicationPlaceField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publisherField.getText().equals("")) {
                    publisherField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (check) {
                    book.setAuthor(authorField.getText());
                    book.setTitle(titleField.getText());
                    book.setISBN(isbnField.getText());

                    book.setGenre(Genre.valueOf(genreField.getSelectedItem().toString()));
                    book.setPublicationPlace(publicationPlaceField.getText());
                    book.setPublicationYear(publicationYearField.getText());
                    book.setPublisher(publisherField.getText());
                    book.setStatus(State.valueOf(statusField.getSelectedItem().toString()));
                    try {
                        bookWebService.updateBook(book);

                        model.setValueAt(book.getAuthor(), table.getSelectedRow(), 1);
                        model.setValueAt(book.getTitle(), table.getSelectedRow(), 2);
                        model.setValueAt(book.getISBN(), table.getSelectedRow(), 3);
                        model.setValueAt(book.getAvailability(), table.getSelectedRow(), 4);
                        model.setValueAt(book.getGenre(), table.getSelectedRow(), 5);
                        model.setValueAt(book.getPublicationPlace(), table.getSelectedRow(), 6);
                        model.setValueAt(book.getPublicationYear(), table.getSelectedRow(), 7);
                        model.setValueAt(book.getPublisher(), table.getSelectedRow(), 8);
                        model.setValueAt(book.getStatus(), table.getSelectedRow(), 9);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(bookPanel, "Cannot update book.\nServer connection problem.",
                                "Oops!", JOptionPane.ERROR_MESSAGE);
                    }

                    frameCreate.dispose();
                }
            }
        });
        return createPanel;
    }

    private JPanel createBook() {
        createPanel = new JPanel();
        createPanel.setLayout(null);

        titleField = new JTextField();
        authorField = new JTextField();
        isbnField = new JTextField();
        genreField = new JComboBox(Genre.values());
        publicationYearField = new JTextField();
        publicationPlaceField = new JTextField();
        publisherField = new JTextField();

        titleLabel = new JLabel("Title");
        authorLabel = new JLabel("Author");
        isbnLabel = new JLabel("ISBN");
        genreLabel = new JLabel("Genre");
        publicationYearLabel = new JLabel("Publication year");
        publicationPlaceLabel = new JLabel("Publication place");
        publisherLabel = new JLabel("Publisher");

        titleLabel.setBounds(10, 15, 150, 20);
        createPanel.add(titleLabel);
        titleField.setBounds(10, 35, 150, 20);
        createPanel.add(titleField);

        authorLabel.setBounds(10, 60, 150, 20);
        createPanel.add(authorLabel);
        authorField.setBounds(10, 80, 150, 20);
        createPanel.add(authorField);

        isbnLabel.setBounds(10, 105, 150, 20);
        createPanel.add(isbnLabel);
        createPanel.add(isbnField);
        isbnField.setBounds(10, 125, 150, 20);

        genreLabel.setBounds(10, 150, 150, 20);
        createPanel.add(genreLabel);
        createPanel.add(genreField);
        genreField.setBounds(10, 170, 150, 20);

        publicationYearLabel.setBounds(10, 195, 150, 20);
        createPanel.add(publicationYearLabel);
        createPanel.add(publicationYearField);
        publicationYearField.setBounds(10, 215, 150, 20);

        publicationPlaceLabel.setBounds(10, 240, 150, 20);
        createPanel.add(publicationPlaceLabel);
        createPanel.add(publicationPlaceField);
        publicationPlaceField.setBounds(10, 260, 150, 20);

        publisherLabel.setBounds(10, 285, 150, 20);
        createPanel.add(publisherLabel);
        createPanel.add(publisherField);
        publisherField.setBounds(10, 305, 150, 20);

        createBookButton = new JButton();
        createBookButton.setText("Create book");
        createBookButton.setBounds(10, 350, 150, 20);
        createPanel.add(createBookButton);
        createBookButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boolean check = true;
                if (titleField.getText().equals("")) {
                    titleField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (authorField.getText().equals("")) {
                    authorField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (isbnField.getText().equals("")) {
                    isbnField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publicationYearField.getText().equals("")) {
                    publicationYearField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publicationPlaceField.getText().equals("")) {
                    publicationPlaceField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (publisherField.getText().equals("")) {
                    publisherField.setBackground(Color.getHSBColor(243, 102, 78));
                    check = false;
                }
                if (check) {
                    BookTO book = new BookTO();
                    book.setAuthor(authorField.getText());
                    book.setTitle(titleField.getText());
                    book.setISBN(isbnField.getText());
                    book.setAvailability(Available.AVAILABLE);
                    book.setGenre(Genre.valueOf(genreField.getSelectedItem().toString()));
                    book.setPublicationPlace(publicationPlaceField.getText());
                    book.setPublicationYear(publicationYearField.getText());
                    book.setPublisher(publisherField.getText());
                    book.setStatus(State.NEW);
                    try {
                        bookWebService.createBook(book);
                        Object[] arr = {
                            book.getId(), book.getAuthor(), book.getTitle(), book.getISBN(), book.getAvailability(), book.getGenre(),
                            book.getPublicationPlace(), book.getPublicationYear(), book.getPublisher(), book.getStatus()
                        };
                        model.addRow(arr);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(bookPanel, "Cannot create book.\nServer connection problem.",
                                "Oops!", JOptionPane.ERROR_MESSAGE);
                    }
                    frameCreate.dispose();
                }
            }
        });
        return createPanel;
    }
}
